﻿using System;
using System.ComponentModel;
using DataLayer.Repo;

namespace DataLayer.Types
{
    public abstract class BaseRecord<T> : IBaseRecord, INotifyPropertyChanged, IEquatable<T>, IComparable<T>, IComparable
        where T : class, IIdentifiableObject
    {
        public virtual event PropertyChangedEventHandler PropertyChanged;

        protected int m_id;
        protected string m_name;

        public virtual int Id
        {
            get
            {
                return m_id;
            }
            set
            {
                m_id = value;
                OnPropertyChanged("Id");
            }
        }

        public virtual string Name
        {
            get
            {
                return m_name;
            }
            set
            {
                m_name = value;
                OnPropertyChanged("Name");
            }
        }


        public virtual void Save(T item)
        {
            if (m_id == 0)
            {
                StructureMap.ObjectFactory.GetInstance<IRepository<T>>().Add(item);
            }
            else
            {
                StructureMap.ObjectFactory.GetInstance<IRepository<T>>().Update(item);
            }
        }

        public virtual void Delete(T item)
        {
            StructureMap.ObjectFactory.GetInstance<IRepository<T>>().Remove(item);
        }


        #region ICloneable Members
        public object Clone()
        {
            return MemberwiseClone();
        }
        #endregion

        #region INotifyPropertyChanged Members

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region IEquatable<T> Members

        public bool Equals(T other)
        {
            return Id == other.Id;
        }

        #endregion

        #region IComparable<T> Members

        public int CompareTo(T other)
        {
            BaseRecord<T> otherRecord = other as BaseRecord<T>;
            if (otherRecord == null) return 1;
            return Name.CompareTo(otherRecord.Name);
        }

        #endregion

        public int CompareTo(object obj)
        {
            BaseRecord<T> other = obj as BaseRecord<T>;
            if (other == null) return 1;
            return Name.CompareTo(other.Name);
        }
    }
}
